const api = require('../../utils/api.js');

Page({
  data: {
    imgBaseUrl: '',
      iconBaseUrl: '',
    isLogout: true,
    avatarUrl: '',
    nickname: '',
    // 新增悬浮窗口相关数据
    showLoginModal: false,  // 控制悬浮窗口显示
  },
  onLoad(){
    this.loadData();
  },
  loadData(){
    this.setData({ imgBaseUrl: api.ENV.imgBaseUrl || '' ,iconBaseUrl: api.ENV.iconBaseUrl || ''});
    var userinfo=wx.getStorageSync('userInfo');
    var isLogout=wx.getStorageSync('isLogout');
    if(userinfo){this.setData({avatarUrl:userinfo.avatarUrl,nickname:userinfo.nickname});}
    else {this.setData({avatarUrl:'',nickname:''});}
    this.setData({isLogout:isLogout});
  },
  onShow(){
    this.loadData();
    try {
      const auth = require('../../utils/auth');
      auth.ensureLogin({ mode: 'silent' });
    } catch (e) {}
  },
  // 点击登录按钮：只显示悬浮窗口，不执行登录请求
  login: function() {
    this.setData({
      showLoginModal: true,  // 显示悬浮窗口
    });
  },
  exit(){
    try {
      const auth = require('../../utils/auth');
      wx.setStorageSync('userInfo', null);
      wx.setStorageSync('isLogout', true);
      wx.setStorageSync('userId', null);
      wx.setStorageSync('userToken', null);
      wx.setStorageSync('loginResult', {});
      // 清除最近一次校验时间
      wx.setStorageSync('lastAuthCheckAt', 0);
    } catch (e) {
      wx.setStorageSync('userInfo', null);
      wx.setStorageSync('isLogout', true);
      wx.setStorageSync('userId', null);
      wx.setStorageSync('userToken', null);
      wx.setStorageSync('loginResult', {});
      wx.setStorageSync('lastAuthCheckAt', 0);
    }
    this.loadData();

  },
  // 隐藏悬浮窗口
  hideLoginModal: function() {
    this.setData({
      showLoginModal: false
    });
  },
  changeavatar:function(e){
    var linkAvatar=e.detail.avatarUrl;
    this.setData({avatarUrl:linkAvatar});
  },
  // 输入昵称时更新临时数据
  onNicknameInput: function(e) {
    this.setData({
      nickname: e.detail.value
    });
  },

  // 确认登录：验证信息后执行登录请求
  confirmLogin: function() {
    // 验证头像和昵称是否填写
    if (!this.data.avatarUrl) {
      wx.showToast({
        title: '请选择头像',
        icon: 'none'
      });
      return;
    }
    if (!this.data.nickname) {
      wx.showToast({
        title: '请输入昵称',
        icon: 'none'
      });
      return;
    }

    // 隐藏悬浮窗口
    this.hideLoginModal();

    // 执行原登录逻辑（wx.login + wx.request）
    wx.login({
      success: (res) => {
        console.log(res.code);
        const code = res.code;
        
        wx.request({
          url: "http://test.uu163yun.com/mapi/Live_2_0/Tourist/Login",
          method: 'POST',
          header: {
            "ApiVersion": "6.0",
            "ApiWay": "API",
            "MerId": "dc529a26P-aecd-4727-86c4-cb62ad24ab99", 
            "VendorId": "350",  
          },
          data: {
            "code": code,
            "endpointCode":"Suse652",
            "endpointVersion":"1.0.0",
          },
          success: (response) => {
            console.log(response.data);
            if (response.data.result !== "NG") {
              const auth = require('../../utils/auth');
              // 登录成功后保存用户信息
              wx.setStorageSync('isLogout', false);
              wx.setStorageSync('userInfo', {
                avatarUrl: this.data.avatarUrl,
                nickname: this.data.nickname
              });
              var loginResult={
                userToken:'',
                userId:''
              };
              loginResult.userToken=response.data.userToken;
              loginResult.userId=response.data.userId;
              wx.setStorageSync('loginResult', loginResult);
              // 记录最近一次服务端校验时间
              try { auth.setAuthCheckTime(Date.now()); } catch (e) {}
              // 更新页面数据
              this.setData({
                isLogout: false,
                avatarUrl: this.data.avatarUrl,
                nickname: this.data.nickname
              });
              wx.showToast({
                title: '登录成功',
                icon: 'success'
              });
            }
          },
          fail: (error) => {
            console.log('登录失败', error);
            wx.showToast({
              title: '登录失败，请重试',
              icon: 'none'
            });
          }
        });
      },
    });
  },
  editSelfInfo(){
    wx.navigateTo({
      url: '/pages/edit/edit',
    })
  }
});